<?php

class Galleries extends CI_Controller
{
    var $data = array ();
    var $translate;
    var $uploads_dir = "./../cms-galleries/gal";
    var $thumb_size = array('w'=>180,'h'=>160);

    function __construct ()
    {
        parent::__construct ();

        if ( !$this->session->userdata ( 'logged_in' ) )
            redirect(site_url('login'));

        $this->load->model ( 'galleries_model' );

        $this->load->helper ( 'inflector' );
        $this->load->config ( 'languages' );
        //$this->translate = & $this->factory->create ( 'translate', 'foo', 'bar' );
        $this->lang->load('common');
    }

    function index ()
    {
        $this->view_all();
    }
    public function view_all ()
    {
        $galleries = $this->galleries_model->find_all();

        $this->firephp->log($galleries);


        $this->data['galleries'] = $galleries;
        $this->data['title'] = "All galleries";
        $this->data['page_title'] = "Galleries";

        $this->template->build ( 'galleries/view_all', $this->data );
    }

    public function view_new_gallery()
    {
		$this->load->model('pages_model');
		$pages = $this->pages_model->find_all();
        $this->data = array_merge ( $this->data, array (
            'post_action' => 'NEW',
			'pages' => $pages
        ) );
        $this->template->build ( 'galleries/new_edit_gallery', $this->data );
    }

    public function view_edit_gallery($gallery_id)
    {
        $gallery = $this->galleries_model->find_id($gallery_id);
		
		$this->load->model('pages_model');
		$pages = $this->pages_model->find_all();
		
        $this->data = array_merge ( $this->data, array (
            'post_action' => 'EDIT',
            'gallery' => $gallery,
			'pages' => $pages
        ) );
        $this->template->build ( 'galleries/new_edit_gallery', $this->data );
    }

    public function view_upload_picture($gallery_id)
    {
        $gallery = $this->galleries_model->find_id($gallery_id);
        $this->data = array_merge ( $this->data, array (
            'post_action' => 'EDIT',
            'gallery' => $gallery
        ) );
        $this->template->build ( 'galleries/upload_picture', $this->data );
    }

    public function view_gallery_pictures($gallery_id)
    {

        $this->load->model('pictures_model');
        $gallery = $this->galleries_model->find_id($gallery_id);
        $pictures = $this->pictures_model->find_by_gallery($gallery_id);
        $this->data = array_merge ( $this->data, array (
            'post_action' => 'EDIT',
            'gallery_path' => 'cms-galleries/gal' . $gallery_id . '/thumbnail/',
            'gallery' => $gallery,
            'pictures' => $pictures
        ) );
        $this->template->build ( 'pictures/view_all', $this->data );
    }


    public function submit()
    {
        $this->firephp->log($_POST);

        //Post data sent by view
        $post = $_POST;

        $post_action = $post['post_action'];

        $data = array (
            'title' => $post['title'],
			'page_id' => $post['page_id']
        );

        $insert_id = null;

        if($post_action == "NEW")
        {

            $this->db->trans_start ();
            $insert_id = $this->galleries_model->insert ( $data );
            $this->db->trans_complete ();

            // make gallery folder based on gallery name, and make path taking base url from config

            if (file_exists("./../cms-galleries"))
                {
                    if(!mkdir('./../cms-galleries/gal' . $insert_id))
                        die('Failed to create folder - cms-gallery level 1');
                }
                else
                {
                    if (mkdir( "./../cms-galleries", 0777))
                    {
                        if(!mkdir('./../cms-galleries/gal' . $insert_id))
                            die('Failed to create folder - cms-gallery level 2');
                    }
                    else
                        die('Failed to create folder - cms-gallery level 0');
                }
            if(file_exists("./../cms-galleries/gal" . $insert_id)){
                if(!mkdir("./../cms-galleries/gal" . $insert_id . "/thumbnail")){
                    die("Failed to create folder cms-gallery/thumbnail");
                }
            }
            
            
        }

        if($insert_id){
            echo json_encode ( array (
                "action" => true,
                "msg" => lang('common.successfullyoperation'),
                "insert_id" => $insert_id ) );
        }
        else
        {

            // If comes to thisd line, error ocured
            echo json_encode ( array (
                'action' => FALSE,
                'msg' => '<p>' . lang('common.thisshouldnothappen') . '</p>'
            ) );
        }

    }

    function delete_gallery ( $gallery_id )
    {
        $this->galleries_model->delete ( $gallery_id );
        // TODO cleanup folders and files within gallery
    }

    function delete_picture ( $picture_id )
    {
        $this->load->model('pictures_model');
        $this->pictures_model->delete ( $picture_id );
        //TODO Clean thumb and picture for this id
    }
    public function upload_picture ()
    {

        $this->firephp->log($_POST);

        //Post data sent by view
        $post = $_POST;

        // GALERY PATH
        $uploads_dir_gal = $this->uploads_dir . $post['gallery_id'];

                $tmp_name = $_FILES["picture"]["tmp_name"];
                $name = $_FILES["picture"]["name"];
                move_uploaded_file($tmp_name, "$uploads_dir_gal/$name");

                $data = array_merge( $this->data, array (
                'name' => $post['name'],
                'alt' => $post['alt'],
                'file_name' => $name,
                'description' => '_desc',
                'gallery_id' => $post['gallery_id']
                ));


        $insert_id = null;

            $this->load->model ( 'pictures_model' );
            $this->firephp->log($data);
            // make gallery folder based on gallery name, and make path taking base url from config
            $this->db->trans_start ();
            $insert_id = $this->pictures_model->insert ( $data );
            $this->db->trans_complete ();

        $this->create_thumbs($post['gallery_id']);

        if($insert_id){
            echo json_encode ( array (
                "action" => true,
                "msg" => lang('common.successfullyoperation'),
                "insert_id" => $insert_id ) );
        }
        else
        {

            // If comes to thisd line, error ocured
            echo json_encode ( array (
                'action' => FALSE,
                'msg' => '<p>' . lang('common.thisshouldnothappen') . '</p>'
            ) );
        }
        
    }

    public function create_thumbs($gallery_id){



            $uploads_dir_gal = $this->uploads_dir . $gallery_id;

            $this->load->model('pictures_model');
            $this->load->library('img_map');

            $pictures = $this->pictures_model->find_by_gallery($gallery_id);


            define("FOLDER_IMAGES",$uploads_dir_gal.'/');            
            define("FOLDER_CACHE",$uploads_dir_gal.'/thumbnail/');
            define("JPEG_QUALITY","90");            
            define("FILEPATH_IMAGE_NOT_FOUND","./assets/img/img_map/blank.jpg");

            //set defines data
            $this->img_map->setImagesFolder(FOLDER_IMAGES);
            $this->img_map->setCacheFolder(FOLDER_CACHE);
            $this->img_map->setErrorImagePath(FILEPATH_IMAGE_NOT_FOUND);
            $this->img_map->setJpegQuality(JPEG_QUALITY);  // end img_map settings

            //insert pictures
            $cnt = count($pictures);
            for($i=0;$i<$cnt;$i++){

                    //echo '<br>'.print_r($dimension).'<br>';

                    //Create Thumbnails
                    $this->img_map->showImage($pictures[$i]['file_name'],$this->thumb_size['w'],$this->thumb_size['h'],"exacttop");

            }
    }
}
?>